package cn.kimming.shirodemo.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {

    private static final long DEFAULT_EXPIREMILLTIME = 2 * 60 * 60 * 1000;
    private static final String SECRET = "kimming";

    public static String createToken(Map<String, Object> claims, long expireMillTime) {
        if (expireMillTime <= 0) {
            expireMillTime = DEFAULT_EXPIREMILLTIME;
        }
        long expireOn = System.currentTimeMillis() + expireMillTime;
        String token = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, generateKey())
                .addClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(expireOn))
                .compact();
        return token;
    }

    public static String createTokenByUserId(Long userId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        return createToken(claims, 0);
    }

    public static Claims verifyToken(String token) {
        return Jwts.parser().setSigningKey(generateKey()).parseClaimsJws(token).getBody();
    }

    public static Long getUserIdByToken(String token) {
        String[] split = token.split("\\.");
        JSONObject jsonObject = JSON.parseObject(new String(Base64.getDecoder().decode(split[1])));
        Long userId = jsonObject.getLong("userId");
        if (userId == null) throw new RuntimeException("token中没有用户id");
        return userId;
    }

    private static Key generateKey() {
        return new SecretKeySpec(SECRET.getBytes(), "AES");
    }

    public static void main(String[] args) {
        String tokenByUserId = createTokenByUserId(1L);
        System.out.println(tokenByUserId);
    }
}
